package utils

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/hex"
	"github.com/google/uuid"
	"math/big"
)

const (
	letterBytes  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	numberBytes  = "0123456789"
	specialBytes = "!@#$%&*()-_=+{}[]|<>,.?/"
)

// 生成随机字符串
func generateRandomStr(length int, charset string) (string, error) {
	b := make([]byte, length)
	limit := big.NewInt(int64(len(charset)))
	for i := range b {
		randInt, err := rand.Int(rand.Reader, limit)
		if err != nil {
			return "", err // proper error handling will be needed here
		}
		b[i] = charset[randInt.Int64()]
	}
	return string(b), nil
}

// RandomAlphaString 生成纯字母随机字符串
func RandomAlphaString(length int) (string, error) {
	return generateRandomStr(length, letterBytes)
}

// RandomNumericString 生成纯字母随机字符串
func RandomNumericString(length int) (string, error) {
	return generateRandomStr(length, numberBytes)
}

// RandomAlphaNumericString 生成字母数字的随机字符串
func RandomAlphaNumericString(length int) (string, error) {
	return generateRandomStr(length, letterBytes+numberBytes)
}

// RandomAlphaNumericSpecialCharString 生成字母数字特殊字符的随机字符串
func RandomAlphaNumericSpecialCharString(length int) (string, error) {
	return generateRandomStr(length, letterBytes+numberBytes+specialBytes)
}

// UUID 生成uuid
func UUID() (string, error) {
	id, err := uuid.NewRandom()
	if err != nil {
		return "", err
	}
	return id.String(), nil
}

// UUID32 生成uuid的32位值
func UUID32() (string, error) {
	id, err := uuid.NewRandom()
	if err != nil {
		return "", err
	}
	md5Sum := md5.Sum([]byte(id.String()))
	return hex.EncodeToString(md5Sum[:]), nil
}

// MapNumberToLetter 数字生成字母
func MapNumberToLetter(number int) string {
	if number >= 1 && number <= 26 {
		charCodeA := 'A'
		charCode := charCodeA + rune(number) - 1
		return string(charCode)
	} else {
		return ""
	}
}
